package handlers

import (
	"data_service/server"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 初始化好友申请业务服务
var friendRequestService = server.NewFriendRequestService()

// SendFriendRequestHandler 发送好友申请
func SendFriendRequestHandler(c *gin.Context) {
	var req struct {
		FromUserID int    `json:"from_user_id" binding:"required"`
		ToUserID   int    `json:"to_user_id" binding:"required"`
		Message    string `json:"message"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	if err := friendRequestService.SendFriendRequest(req.FromUserID, req.ToUserID, req.Message); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "好友申请发送成功"})
}

// GetFriendRequestsHandler 获取好友申请列表
func GetFriendRequestsHandler(c *gin.Context) {
	userIDStr := c.Query("user_id")
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户ID"})
		return
	}

	requests, err := friendRequestService.GetFriendRequests(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取好友申请失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": requests})
}

// RespondToFriendRequestHandler 处理好友申请
func RespondToFriendRequestHandler(c *gin.Context) {
	requestIDStr := c.Param("id")
	requestID, err := strconv.ParseUint(requestIDStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的申请ID"})
		return
	}

	var req struct {
		UserID int    `json:"user_id" binding:"required"`
		Action string `json:"action" binding:"required"` // accept 或 reject
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	// 验证action值
	if req.Action != "accepted" && req.Action != "rejected" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的操作类型"})
		return
	}

	if err := friendRequestService.RespondToFriendRequest(uint(requestID), req.UserID, req.Action); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	actionText := "接受"
	if req.Action == "rejected" {
		actionText = "拒绝"
	}

	c.JSON(http.StatusOK, gin.H{"message": "好友申请" + actionText + "成功"})
}
